#include "advertisingboard.h"
#include<QTimer>
#include<QPainter>
#include<QPaintEvent>
#include<QPainterPath>

static const int G_Radius=5;

AdvertisingBoard::AdvertisingBoard(QWidget *parent)
    : QWidget{parent},
    timer(new QTimer(this))
{
    connect(timer,&QTimer::timeout,this,qOverload<>(&AdvertisingBoard::update));
    this->timer->start(3000);
}

AdvertisingBoard::~AdvertisingBoard()
{
    for (auto pix:this->posters) {
        if(pix)
            delete pix;
    }
    this->posters.clear();
}

void AdvertisingBoard::addPoster(const QPixmap &posterPix)
{
    QPixmap* pix=new QPixmap(posterPix);
    this->posters.append(pix);
}

void AdvertisingBoard::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    painter.setRenderHint(QPainter::Antialiasing,true);

    if(this->posters.isEmpty()){
        QWidget::paintEvent(event);
        return ;
    }

    static int posterIndex=0;
    QPixmap img=(this->posters[posterIndex])->scaled(this->size(),Qt::KeepAspectRatio);
    //将图片变成圆角
    QPainterPath path;
    path.addRoundedRect(this->rect(),10,10);
    painter.setClipPath(path);

    //绘制广告图
    painter.drawPixmap(this->rect(),img);
    posterIndex=(++posterIndex)%this->posters.size();

    //绘制广告播放进度
    QPoint drawStartPos=QPoint((this->width()-G_Radius*3*this->posters.size())/2,this->height()-10);

    painter.setPen(Qt::NoPen);

    for(int i=0;i<this->posters.size();++i)
    {
        if(i==posterIndex)
            painter.setBrush(Qt::red);
        else
            painter.setBrush(Qt::white);

        painter.drawEllipse(drawStartPos,G_Radius,G_Radius);
        drawStartPos.setX(drawStartPos.x()+G_Radius*3);
    }


    QWidget::paintEvent(event);

}
